package com.mszlu.blog.common.aop;

import com.mszlu.blog.service.ThreadService;
import com.mszlu.blog.utils.IpUtils;
import com.mszlu.blog.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lfw
 * @Date: 2022/06/11/20:21
 * @Description:
 */
@Aspect
@Slf4j
@Configuration
public class QuestionViewAspect {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取当前的ServletRequest
     * @return
     */
    protected HttpServletRequest servletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.mszlu.blog.common.aop.QuestionView)")
    public void questionViewPointCut(){}


    /**
     * 切入处理，环绕通知
     * @param joinPoint
     * @return
     */
    @Around("questionViewPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object questionId = args[0];
        Object obj = null;
        try {
            // 获取请求的ip
            String ipAddr = IpUtils.getIpAddr(servletRequest());
            log.info("请求Ip：{}",ipAddr);
            // 设置存入的key
            String key = "QUESTION_ID" + questionId;
            // 将存入到缓存中
            Long count = this.redisUtil.add(key, ipAddr);
            if (count == 0){
                log.info("该Ip：{},访问量已经访问过了",ipAddr);
            }
            Long increment = redisTemplate.boundValueOps("StringKey").increment(1L);
            System.out.println(increment);
            Long size = redisUtil.size(key);
            System.out.println(size);

            obj = joinPoint.proceed();
        }catch (Exception e){
            e.fillInStackTrace();
        }
        return obj;
    }
}

